package com.jdew.thkj.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.bean.UserBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    private IWXAPI api;
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;
    private String headimgurl;
    private String wx_message;
    private String openId;
    private String state;
    private String sessionId;
    private String seceret;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        api = WXAPIFactory.createWXAPI(this, AppConfig.APPID, false);
        api.handleIntent(getIntent(), this);
        getSessionId();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onReq(BaseReq arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == RETURN_MSG_TYPE_SHARE) {
                    wx_message = "发送成功";
                    Toast.makeText(this, wx_message, Toast.LENGTH_LONG).show();
                    finish();
                } else if (resp.getType() == RETURN_MSG_TYPE_LOGIN) {
                    SendAuth.Resp req = ((SendAuth.Resp) resp);
                    String code = ((SendAuth.Resp) resp).code;
                    state=req.state;
                    getAccess_token(code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                wx_message = "发送返回";
                Toast.makeText(this, wx_message, Toast.LENGTH_LONG).show();
                this.finish();
                break;
            default:
                this.finish();
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + AppConfig.APPID
                + "&secret="
                + "bd30b0d1f97b66d469d4c5a00f43dd63"
                + "&code="
                + code
                + "&grant_type=authorization_code";
        Request.Builder builder = new Request.Builder().url(path);

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                JSONObject jsonObject = JSONObject.parseObject(result);
                if(null==jsonObject){
                    ToastUtils.getInstance(WXEntryActivity.this).showMessage("网络出现了一点小问题,请重新登录!");
                    finish();
                    Looper.loop();
                }
                if(null!=jsonObject.getString("openid")){
                    openId = jsonObject.getString("openid").toString().trim();
                }else{
                    ToastUtils.getInstance(WXEntryActivity.this).showMessage("请绑定微信后登录!");
                }
                String access_token = jsonObject.getString("access_token").toString().trim();
                getUserMesg(access_token, openId);
                Looper.loop();
            }
        });
    }

    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */

    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Request.Builder builder = new Request.Builder().url(path);
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                JSONObject jsonObject = JSONObject.parseObject(result);
                String nickname = jsonObject.getString("nickname");
                headimgurl = jsonObject.getString("headimgurl");
                openId = jsonObject.getString("openid");
                sp.getString("nickname", nickname);
                sp.getString("headimgurl", headimgurl);
                editor.apply();
                if (state.equals("wechat_sdk_demo")) {
                    SetUserWxId();
                } else if(state.equals("diandi_wx_login")){
                    wxLogin(openId);
                }
                Looper.loop();
            }
        });
    }

    public void SetUserWxId() {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetUserWxId(openId, sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"OppenId"+openId+"UserPhone"+sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                UpWxloadAvatar();
                editor.putString("UserWxId", openId);
                editor.putString("UserImgUrl", headimgurl);
                editor.apply();
            }
        });
    }

    public void UpWxloadAvatar() {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        HashMap<String,Object> map=new HashMap();
        map.put("UserPhone",sp.getString("userPhone",""));
        map.put("UserImgUrl",headimgurl);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).UpWxloadAvatar(map, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"UserPhone"+sp.getString("userPhone", "")+"UserImgUrl"+headimgurl)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    Toast.makeText(WXEntryActivity.this,"微信绑定成功", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
        });
    }

    public void wxLogin(String openId) {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        HashMap<String,Object> map=new HashMap();
        map.put("UserWxId",openId);
        map.put("AndroidOrIos","0");
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).UserWxLogin(sessionId,map,RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"UserWxId"+openId+"AndroidOrIos0")).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<UserBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(WXEntryActivity.this).showMessage("微信登录异常");
                finish();
            }

            @Override
            public void onNext(UserBean bean) {
                if (bean.getCode().equals("0")) {
                    editor.putString("userName", bean.getData().getUserName());
                    editor.putString("userPhone", bean.getData().getUserPhone());
                    editor.putString("Alias", bean.getData().getUserPhone());
                    editor.putString("psw", bean.getData().getUserPwd());
                    editor.putString("UserWxId", bean.getData().getUserWxId());
                    editor.putString("userId", bean.getData().getId());
                    editor.putString("mpid", bean.getData().getUserPid());
                    editor.putString("UserImgUrl", bean.getData().getUserImgUrl());
                    editor.putString("UserSjPhone", bean.getData().getUserSjPhone());
                    editor.putString("Adzoneid", bean.getData().getUserPid().split("_")[3]);
                    editor.putString("Siteid", bean.getData().getUserPid().split("_")[2]);
                    editor.putString("SpareOne", bean.getData().getSpareOne());  //邀请码
                    editor.putString("SpareTwo", bean.getData().getSpareTwo());  //0是高级吗 1是低级码
                    editor.putString("nickName", bean.getData().getSpareThree());
                    editor.putString("UserSjPhone", bean.getData().getUserSjPhone());
                    editor.putString("AliAccount", bean.getData().getUserAlipay());
                    editor.apply();
                    ToastUtils.getInstance(WXEntryActivity.this).showMessage("微信登录成功");
                    startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
                    finish();
                } else if (bean.getCode().equals("-1")) {
                    ToastUtils.getInstance(WXEntryActivity.this).showMessage(bean.getMessage());
                    finish();
                } else if (bean.getCode().equals("2")) {
                    ToastUtils.getInstance(WXEntryActivity.this).showMessage(bean.getMessage());
                    finish();
                }
            }
        });
    }
    public void getSessionId() {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken",""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    sessionId = json.getString("message");
                    seceret = json.getString("data");
                    editor.putString("seceret",seceret);
                    editor.apply();
                }
            }
        });
    }
}
